<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="账户信息" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入账户信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流水日期">
        <el-date-picker
          v-model="daterangeFlowDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="流水类型" prop="flowTypeName">
        <el-input
          v-model="queryParams.flowTypeName"
          placeholder="请输入流水类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账户有无问题" prop="isAccount">
        <el-select v-model="queryParams.isAccount" placeholder="请选择账户有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="流水类型有无问题" prop="isType">
        <el-select v-model="queryParams.isType" placeholder="请选择流水类型有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注有无问题" prop="isRemark">
        <el-select v-model="queryParams.isRemark" placeholder="请选择备注有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据整体有无问题" prop="noWrong">
        <el-select v-model="queryParams.noWrong" placeholder="请选择导入有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['work:flowTotal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['work:flowTotal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:flowTotal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="info" 
          plain 
          icon="el-icon-upload2" 
          size="mini" 
          @click="handleImport" 
          v-hasPermi="['work:flowTotal:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['work:flowTotal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="flowTotalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" width="55" align="center" prop="ids" />
      <el-table-column label="账户信息" align="center" prop="accountName" />
      <el-table-column label="流水日期" align="center" prop="flowDate" width="180" />
      <el-table-column label="摘要" align="center" prop="abstracts" />
      <el-table-column label="流水类型" align="center" prop="flowTypeName" />
      <el-table-column label="流水金额" align="center" prop="flow" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="二级金额" align="center" prop="level2Flow" />
      <el-table-column label="数据有无问题" align="center" prop="noWrong" >
        <template slot-scope="scope">
          <span>{{ scope.row.noWrong === '0' ? '有问题' : (scope.row.noWrong === '1' ? '没问题' : scope.row.noWrong) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['work:flowTotal:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['work:flowTotal:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改总流水合计对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <div v-if="form.noWrong==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前页面整体都没有问题，可以正常使用！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前页面存在不标准数据类型，请尽快修改！
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典账户" prop="accountId">
              <el-select v-model="form.accountId" placeholder="请选择字典账户" filterable @change="handleAccountChange">
                <el-option
                  v-for="account in accountOptions"
                  :key="Number(account.ids)"
                  :label="account.accountName"
                  :value="Number(account.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入账户" prop="accountName">
              <el-input v-model="form.accountName" placeholder="请输入导入账户" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isAccount==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前账户名称与字典账户一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前账户名称与字典账户不一致！
            </div> 
          </el-col>
          <el-col :span="24">
            <el-form-item label="流水日期" prop="flowDate">
              <el-date-picker clearable
                v-model="form.flowDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择流水日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="摘要" prop="abstracts">
              <el-input v-model="form.abstracts" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典流水类型" prop="flowTypeId">
              <el-select v-model="form.flowTypeId" placeholder="请选择字典流水类型" filterable @change="handleFlowTypeChange" >
                <el-option
                  v-for="dict in flowTypeOptions"
                  :key="Number(dict.ids)"
                  :label="dict.dictName"
                  :value="Number(dict.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入流水类型" prop="flowTypeName">
              <el-input v-model="form.flowTypeName" placeholder="请输入导入流水类型" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isType==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前流水类型与字典类型一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前流水类型与字典类型不一致！
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="流水金额" prop="flow">
              <el-input-number v-model="form.flow" placeholder="请输入流水金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典备注" prop="remarkId">
              <el-select v-model="form.remarkId" placeholder="请选择字典备注" filterable @change="handleRemarkChange" >
                <el-option
                  v-for="dict in remarkOptions"
                  :key="Number(dict.ids)"
                  :label="dict.dictName"
                  :value="Number(dict.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isRemark==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注不一致！
            </div>     
          </el-col>
          <el-col :span="24">
            <el-form-item label="二级金额" prop="level2Flow">
              <el-input-number v-model="form.level2Flow" placeholder="请输入二级金额" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.titleImport" :visible.sync="upload.openImport" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFlowTotal, getFlowTotal, delFlowTotal, addFlowTotal, updateFlowTotal } from "@/api/work/flowTotal"
import { findYwDictList } from "@/api/work/ywDict"
import { findAllAccountList } from "@/api/work/account"
import { getToken } from "@/utils/auth";

export default {
  name: "FlowTotal",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总流水合计表格数据
      flowTotalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 二级金额时间范围
      daterangeFlowDate: [],
      // 账户类型选项
      accountOptions: [],
      // 字典流水类型选项
      flowTypeOptions: [],
      // 字典备注类型选项
      remarkOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountName: null,
        isAccount: null,
        flowDate: null,
        abstracts: null,
        flowTypeName: null,
        isType: null,
        remark: null,
        isRemark: null,
        noWrong: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        accountId: [
          { required: true, message: "字典账户不能为空", trigger: "blur" }
        ],
        accountName: [
          { required: true, message: "导入账户不能为空", trigger: "blur" }
        ],
        flowDate: [
          { required: true, message: "流水日期不能为空", trigger: "blur" }
        ],
        abstracts: [
          { required: true, message: "摘要不能为空", trigger: "blur" }
        ],
        flowTypeId: [
          { required: true, message: "字典流水类型不能为空", trigger: "blur" }
        ],
        flowTypeName: [
          { required: true, message: "导入流水类型不能为空", trigger: "blur" }
        ],
        flow: [
          { required: true, message: "流水金额不能为空", trigger: "blur" }
        ],
        remarkId: [
          { required: true, message: "字典备注不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "导入备注不能为空", trigger: "blur" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入弹窗）
        openImport: false,
        // 弹出层标题（自己填写）
        titleImport: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址,即后端接口地址
        url: process.env.VUE_APP_BASE_API + "/work/flowTotal/importData"
      },
    }
  },
  created() {
    this.getList()
    this.getAccountOptions()
    this.getFlowTypeOptions()
    this.getRemarkOptions()
  },
  methods: {
    /** 获取账户类型选项 */
    getAccountOptions() {
      findAllAccountList().then(response => {
        this.accountOptions = response.data || []
      })
    },
    /** 字典流水类型选择变更处理 */
    handleAccountChange(value) {
      // 根据选中的accountId查找对应的dictName
      const selectedAccount = this.accountOptions.find(item => item.ids === value);
      if (selectedAccount) {
        this.form.accountName = selectedAccount.accountName;
      } else {
        this.form.accountName = '';
      }
    },
    /** 获取字典流水类型选项 */
    getFlowTypeOptions() {
      findYwDictList("flowType").then(response => {
        this.flowTypeOptions = response.data || []
        // 转换字段类型
        if (this.flowTypeOptions.ids) {
          this.flowTypeOptions.ids = Number(this.flowTypeOptions.ids)
        }
      })
    },
    /** 字典流水类型选择变更处理 */
    handleFlowTypeChange(value) {
      // 根据选中的flowTypeId查找对应的dictName
      const selectedFlowType = this.flowTypeOptions.find(item => item.ids === value);
      if (selectedFlowType) {
        this.form.flowTypeName = selectedFlowType.dictName;
      } else {
        this.form.flowTypeName = '';
      }
    },
    /** 获取字典备注类型选项 */
    getRemarkOptions() {
      findYwDictList("flowRemark").then(response => {
        this.remarkOptions = response.data || []
      })
    },
    /** 字典备注选择变更处理 */
    handleRemarkChange(value) {
      // 根据选中的remarkId查找对应的dictName
      const selectedRemark = this.remarkOptions.find(item => item.ids === value);
      if (selectedRemark) {
        this.form.remark = selectedRemark.dictName;
      } else {
        this.form.remark = '';
      }
    },
    /** 查询总流水合计列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeFlowDate && '' != this.daterangeFlowDate) {
        this.queryParams.params["beginFlowDate"] = this.daterangeFlowDate[0]
        this.queryParams.params["endFlowDate"] = this.daterangeFlowDate[1]
      }
      listFlowTotal(this.queryParams).then(response => {
        this.flowTotalList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ids: null,
        accountId: null,
        accountName: null,
        isAccount: null,
        flowDate: null,
        abstracts: null,
        flowTypeId: null,
        flowTypeName: null,
        isType: null,
        flow: null,
        remarkId: null,
        remark: null,
        isRemark: null,
        level2Flow: null,
        noWrong: null,
        addTime: null,
        upTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeFlowDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ids)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加总流水合计"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const ids = row.ids || this.ids
      getFlowTotal(ids).then(response => {
        this.form = response.data

        this.open = true
        this.title = "修改总流水合计"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ids != null) {
            updateFlowTotal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addFlowTotal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const idss = row.ids || this.ids
      this.$modal.confirm('是否确认删除总流水合计编号为"' + idss + '"的数据项？').then(function() {
        return delFlowTotal(idss)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('work/flowTotal/export', {
        ...this.queryParams
      }, `flowTotal_${new Date().getTime()}.xlsx`)
    },
    /**导入excel表*/
    handleImport() {
      this.upload.titleImport = "导入流水合计表";
      this.upload.openImport = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('work/flowTotal/importTemplate', {
        ...this.queryParams
      }, `流水合计模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>
